const async = require('async')

const pageQuery = function (pageNum, pageSize, Model, populate, queryParams, sortParams) {
    return new Promise((resolve, reject) => {
        const start = (pageNum - 1) * pageSize
        async.parallel({
            count: function (done) {  // 查询数量
                Model.count(queryParams).exec(function (err, count) {
                    done(err, count)
                })
            },
            records: function (done) {   // 查询一页的记录
                Model.find(queryParams).skip(start).limit(pageSize).populate(populate).sort(sortParams).exec(function (err, doc) {
                    done(err, doc)
                })
            }
        }, function (err, results) {
            const total = Number(results.count)
            const $page = {
                list: results.records,
                pageNum,
                pageSize,
                total,
                pageCount: Math.ceil(total / pageSize)
            }
            if (err) reject(err)
            else resolve($page)
        })
    })
}

module.exports = {
    pageQuery: pageQuery
}